<template>
  <div class="af_jurisdiction" v-loading="loading">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="选择角色">
        <el-select v-model="roleId" placeholder="请选择角色" @change="changeRole">
          <el-option v-for="item in roleList" :key="item.id" :label="item.title" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择权限" v-if="!loading">
        <div v-for="item in jurisdictionList" :key="item.id">
          <span class="authorityName">{{ item.name }}</span>
          <el-checkbox-group v-model="item.authority" @change="saveAuthByRoleId">
            <el-checkbox :label="2">编辑权限</el-checkbox>
            <el-checkbox :label="1">查看权限</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '../../api/http';
import _ from 'lodash';
export default {
  data() {
    return {
      loading: false,
      roleList: [],
      jurisdictionList: [],
      form: {},
      roleId: '',
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      this.loading = true;
      this.$api.af_jurisdiction
        .getList({
          page: 1,
          pageSize: 10000,
        })
        .then(res => {
          this.roleList = res.data;
          this.roleId = this.roleId ? this.roleId : this.roleList[0].id;
          this.changeRole(this.roleId);
          this.loading = false;
        });
    },
    // 选择角色
    changeRole(val = 1) {
      const index = this.roleList.findIndex(item => item.id === val);
      this.jurisdictionList = JSON.parse(this.roleList[index].functions);
      this.jurisdictionList.forEach(item => {
        if (item.authority === 0) {
          item.authority = [0];
        } else if (item.authority === 1) {
          item.authority = [0, 1];
        } else {
          item.authority = [0, 1, 2];
        }
      });
    },
    // 保存当前角色下的权限
    // /user/api/authority/{roleId}
    saveAuthByRoleId() {
      this.jurisdictionList.forEach(item => {
        if (_.indexOf(item.authority, 2) !== -1) {
          item.authority = 2;
        } else if (_.indexOf(item.authority, 1) !== -1) {
          item.authority = 1;
        } else {
          item.authority = 0;
        }
      });
      this.loading = true;
      request.put(`/user/api/authority/${this.roleId}`, this.jurisdictionList).then(async res => {
        await this.getRoleList();
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss">
.af_jurisdiction {
  .authorityName {
    display: inline-block;
    padding-right: 20px;
    width: 150px;
    text-align: right;
  }
  .el-checkbox-group {
    display: inline-block;
  }
}
</style>
